package com.share.web.servlet.init;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 说明：加载所有树状菜单
 * <br/>作者：杨浩泉
 * <br/>日期：2010-8-30
 */
public class LoadTreeXml extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	private Map<String,String> treeMap ;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response) ;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/xml; charset=UTF-8");   
		
		this.treeMap = createXMLData(request.getSession().getServletContext()) ;
		
        String content = treeMap.get("tree" + Integer.parseInt(request.getParameter("num"))) ;  
        
        response.getWriter().write(content);   
		
	}

	
	@Override
	public void init(ServletConfig config) throws ServletException {
		try {
			this.treeMap = createXMLData(config.getServletContext()) ;
			config.getServletContext().setAttribute("treex", this.treeMap) ;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static Map<String,String> createXMLData(ServletContext sc) throws IOException {   
		String treePath = sc.getRealPath("/WEB-INF/tree") ;
		
		File file = new File(treePath) ;
		FileInputStream fis = null ;
		InputStreamReader isr = null ;
		BufferedReader br = null ;
		StringBuilder sb = null ;
		Map<String,String> treeMap = new HashMap<String,String>() ;
		
		for(int i=1; i<=file.listFiles().length; i++) {
			fis = new FileInputStream(treePath+"/tree"+i+".xml") ;
			
			isr = new InputStreamReader(fis,"UTF-8") ; 
			
			br = new BufferedReader(isr) ;
			
			sb = new StringBuilder();

			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line);
				sb.append("\r\n");
			}
		  	treeMap.put("tree"+ i, sb.toString()) ;
		}
		
		return treeMap ;
    }   

	
}
